package com.atguigu.tingshu.common.threadpool;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @BelongsProject: tingshu-backend
 * @BelongsPackage: com.atguigu.tingshu.common.threadpool
 * @Author: coilk
 * @CreateTime: 2025-03-19  18:56
 * @Description:
 * @Version: 1.0
 */
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolAutoConfiguration {
    @Value("${spring.application.name}")
    private String appName;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolProperties threadPoolProperties){
        int corePoolSize = threadPoolProperties.getCorePoolSize();
        int maximumPoolSize = threadPoolProperties.getMaxPoolSize();
        long ttl = 30L;
        TimeUnit timeUnit = TimeUnit.SECONDS;

        LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(threadPoolProperties.getQueueSize());

        ThreadFactory threadFactory = new ThreadFactory() {
            AtomicInteger atomicInteger = new AtomicInteger(0);  //
            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("my-customer-【" + appName + "】-" + atomicInteger.incrementAndGet());
                return thread;
            }
        };

        RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                logger.error("提交给线程池的任务：{}，被拒绝了,请及时关注!", r);
                throw new RejectedExecutionException("提交给线程池的任务被拒绝了");
            }
        };

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                ttl,
                timeUnit,
                blockingQueue,
                threadFactory,
                rejectedExecutionHandler
        );

        return threadPoolExecutor;
    }

}
